package com.agriculture.controller;

import com.agriculture.common.Result;
import com.agriculture.domain.Product;
import com.agriculture.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/api/products")
public class ProductController {
    @Autowired
    private ProductService productService;

    @PostMapping
    public Result<?> createProduct(
            @RequestBody Product product,
            @RequestParam String ownerType,
            @RequestParam Long userId) {
        try {
            product.setOwnerId(userId);
            product.setOwnerType(ownerType);
            product.setStatus("on_sale");
            
            if ("dealer".equals(ownerType)) {
                product.setType("processed");
            } else if ("farmer".equals(ownerType)) {
                product.setType("agricultural");
            }
            
            if (product.getPrice() == null) {
                return Result.error("商品价格不能为空");
            }
            
            if (product.getProductName() == null || product.getProductName().trim().isEmpty()) {
                return Result.error("商品名称不能为空");
            }
            
            Product createdProduct = productService.createProduct(product);
            return Result.success(createdProduct);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getProduct(@PathVariable Long id) {
        return ResponseEntity.ok(productService.getProductById(id));
    }

    @GetMapping("/farmer/{farmerId}")
    public ResponseEntity<?> getProductsByFarmer(@PathVariable Long farmerId) {
        return ResponseEntity.ok(productService.findByOwner(farmerId, "farmer"));
    }

    @GetMapping("/search")
    public ResponseEntity<?> searchProducts(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category) {
        return ResponseEntity.ok(productService.searchProducts(keyword, category));
    }
} 